package com.magima.utils.audio;

import java.io.IOException;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;

public class AudioUtil {
	private static MediaRecorder mRecorder = null;
	public static void startRecording(Context context, String filename, MediaRecorder.OnErrorListener onError){
		if ( isRecording() )
			return;
		try {
			mRecorder = new MediaRecorder();
	        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
	        mRecorder.setOutputFile(filename);
	        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	        mRecorder.setOnErrorListener(onError);
	        mRecorder.prepare();
	        
	        mRecorder.start();
		} catch ( Exception e ){
			mRecorder = null;
		}
	}
	
	public static void stopRecording() {
		if (mRecorder!=null) {
			mRecorder.stop();
			mRecorder.release();
			mRecorder = null;
		}
    }
	
	public static boolean isRecording(){
		return mRecorder != null;
	}
	
	private static MediaPlayer mPlayer = null;
	public static void startPlaying(String filename, 
			 MediaPlayer.OnPreparedListener listener1,
			 MediaPlayer.OnCompletionListener listener2,
			 MediaPlayer.OnErrorListener listener3) {
		if ( isPlaying() ) {
			stopPlaying();
		}
        mPlayer = new MediaPlayer();
        try {
        	mPlayer.setOnPreparedListener(listener1);
            mPlayer.setOnCompletionListener(listener2);
            mPlayer.setOnErrorListener(listener3);
            mPlayer.setDataSource(filename);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
        	if ( listener3 != null )
        		listener3.onError(mPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
        }
    }

	public static void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }
	
	public static void togglePlaying(String filename, MediaPlayer.OnPreparedListener listener1,
			MediaPlayer.OnCompletionListener listener2, MediaPlayer.OnErrorListener listener3){
		if ( isPlaying() ) {
			mPlayer.setOnPreparedListener(null);
            mPlayer.setOnCompletionListener(null);
            if ( listener2 != null )
            	listener2.onCompletion(mPlayer);
			stopPlaying();
		} else
			startPlaying(filename, listener1, listener2, listener3);
	}
	
	public static boolean isPlaying(){
		if ( mPlayer == null )
			return false;
		return mPlayer.isPlaying();
	}
	
	public static int getMaxAmplitude(){
		if (mRecorder!=null)
			return mRecorder.getMaxAmplitude();
		return -1;
	}
	
	public static int getLength(Context context, String path){
		int length = 0;
		try {
			MediaPlayer mp = MediaPlayer.create(context, Uri.parse(path));
			length = mp.getDuration();
			mp = null;
		} catch ( Exception e) {
			e.printStackTrace();
		}
		return length;
	}
}
